package cn.itcast.bos.web.action.report;

import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.service.take_delivery.WayBillService;
import cn.itcast.bos.utils.FileUtils;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.List;

// 导出运单 报表
@Controller
public class ReportContorller {

	@Autowired
	private WayBillService wayBillService;

	/**
	 * 使用POI技术生成xls文件
	 */
	@RequestMapping("report_exportXls")
	public void exportXls(WayBill wayBill, HttpServletRequest request, HttpServletResponse response) throws IOException {
		// -------------------查询出 满足当前条件 结果数据-------------------
		List<WayBill> wayBills = wayBillService.findWayBills(wayBill);

		// -------------------生成Excel文件-------------------
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
		HSSFSheet sheet = hssfWorkbook.createSheet("运单数据");
		// 表头
		HSSFRow headRow = sheet.createRow(0);
		headRow.createCell(0).setCellValue("运单号");
		headRow.createCell(1).setCellValue("寄件人");
		headRow.createCell(2).setCellValue("寄件人电话");
		headRow.createCell(3).setCellValue("寄件人地址");
		headRow.createCell(4).setCellValue("收件人");
		headRow.createCell(5).setCellValue("收件人电话");
		headRow.createCell(6).setCellValue("收件人地址");
		// 表格数据
		for (WayBill way : wayBills) {
			HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);	//在最后一行下面再创建一行
			dataRow.createCell(0).setCellValue(way.getWayBillNum());	//运单号
			dataRow.createCell(1).setCellValue(way.getSendName());		//寄件人
			dataRow.createCell(2).setCellValue(way.getSendMobile());	//寄件人电话
			dataRow.createCell(3).setCellValue(way.getSendAddress());	//寄件人地址
			dataRow.createCell(4).setCellValue(way.getRecName());		//收件人
			dataRow.createCell(5).setCellValue(way.getRecMobile());		//收件人电话
			dataRow.createCell(6).setCellValue(way.getRecAddress());	//收件人地址
		}

		// -------------------下载导出-------------------
		// 设置头信息
		response.setContentType("application/vnd.ms-excel");
		String filename = "运单数据.xls";
		String agent = request.getHeader("user-agent");
		filename = FileUtils.encodeDownloadFilename(filename, agent);
		response.setHeader("Content-Disposition", "attachment;filename=" + filename);

		//获得输出流，输出文件
		ServletOutputStream outputStream = response.getOutputStream();
		hssfWorkbook.write(outputStream);

		// 关闭
		hssfWorkbook.close();
	}

	/**
	 * 使用itext生成pdf文件
	 */
	@RequestMapping("report_exportPdf")
	public void exportPdf( WayBill wayBill, HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
		// -------------------查询出 满足当前条件 结果数据-------------------
		List<WayBill> wayBills = wayBillService.findWayBills(wayBill);

		// -------------------下载导出-------------------
		// 设置头信息
		response.setContentType("application/pdf");
		String filename = "运单数据.pdf";
		String agent = request.getHeader("user-agent");
		filename = FileUtils.encodeDownloadFilename(filename, agent);
		response.setHeader("Content-Disposition", "attachment;filename=" + filename);

		// -------------------生成PDF文件-------------------
		Document document = new Document();
		PdfWriter.getInstance(document, response.getOutputStream());
		document.open();
		// 写PDF数据
		// 向document 生成pdf表格
		Table table = new Table(7);
		table.setWidth(80); // 宽度
		table.setBorder(1); // 边框
		table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); 	// 水平对齐方式
		table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP); 		// 垂直对齐方式

		// 设置表格字体
		BaseFont cn = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
		Font font = new Font(cn, 10, Font.NORMAL, Color.BLUE);

		// 写表头
		table.addCell(buildCell("运单号", font));
		table.addCell(buildCell("寄件人", font));
		table.addCell(buildCell("寄件人电话", font));
		table.addCell(buildCell("寄件人地址", font));
		table.addCell(buildCell("收件人", font));
		table.addCell(buildCell("收件人电话", font));
		table.addCell(buildCell("收件人地址", font));
		
		// 写数据，不需要考虑换行，会自动换行
		for (WayBill way : wayBills) {
			table.addCell(buildCell(way.getWayBillNum(), font));
			table.addCell(buildCell(way.getSendName(), font));
			table.addCell(buildCell(way.getSendMobile(), font));
			table.addCell(buildCell(way.getSendAddress(), font));
			table.addCell(buildCell(way.getRecName(), font));
			table.addCell(buildCell(way.getRecMobile(), font));
			table.addCell(buildCell(way.getRecAddress(), font));
		}
		
		// 将表格加入文档
		document.add(table);

		document.close();

	}

	private Cell buildCell(String content, Font font) throws BadElementException {
		Phrase phrase = new Phrase(content, font);
		return new Cell(phrase);
	}

	/**
	 * 使用JasperReport根据模板生成PDF报表文件
	 * 这个模板使用java实体类的字段，所以这里生成的报表数据是根据查询到的结果生成的
	 */
	@RequestMapping("report_exportJasperPdf")
	public void exportJasperPdf(WayBill wayBill, HttpServletRequest request, HttpServletResponse response ) throws IOException, DocumentException, JRException, SQLException {
		// -------------------查询出 满足当前条件 结果数据-------------------
		List<WayBill> wayBills = wayBillService.findWayBills(wayBill);

		// -------------------下载导出-------------------
		// 设置头信息
		response.setContentType("application/pdf");
		String filename = "运单数据.pdf";
		String agent = request.getHeader("user-agent");
		filename = FileUtils.encodeDownloadFilename(filename, agent);
		response.setHeader("Content-Disposition", "attachment;filename=" + filename);

		// -------------------根据 jasperReport模板 生成pdf-------------------
		// 读取模板文件
		String jrxml = request.getSession().getServletContext().getRealPath("/WEB-INF/jasper/waybill_search.jrxml");
		JasperReport report = JasperCompileManager.compileReport(jrxml);

		// 设置模板数据
		// Parameter变量
		Map<String, Object> paramerters = new HashMap<String, Object>();
		paramerters.put("company", "阿里巴巴网络技术有限公司");
		// Field变量
		JasperPrint jasperPrint = JasperFillManager.fillReport(report, paramerters, new JRBeanCollectionDataSource(wayBills));
		// 生成PDF客户端
		JRPdfExporter exporter = new JRPdfExporter();
		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
		exporter.exportReport();// 导出
		response.getOutputStream().close();
	}
}